package com.tledu.spring.core.interceptor;

import com.tledu.spring.core.constants.CommonConstants;
import com.tledu.spring.domain.Cus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/7/5 11:04
 */
public class AutoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // true代表如果没有session就会创建一个session，false没有session就会返回null
        HttpSession session = request.getSession(true);
        Cus user = (Cus) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        if (user == null) {
            request.setAttribute("msg", "无权限请先登录");
            request.getRequestDispatcher("/login").forward(request, response);
            // 终止后续请求
            return false;
        }
        return true;
    }
}
